package com.dgtech.sss.socketdemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;


public class ServerThread extends Thread {
    Socket socket = null;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        OutputStream os = null;
        PrintWriter pw = null;
        try {
            String info = null;
            StringBuilder stringBuilder = new StringBuilder();
            //步骤③建立连接后,通过输入流读取客户端发送的请求信息
            //获取输入流
            is = socket.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            while ((info = br.readLine()) != null) {
                stringBuilder.append(info);
            }
            socket.shutdownInput();
           /* try {
                Thread.sleep(6*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }*/
            String[] split = stringBuilder.toString().split(":");
            String name = split[0];
            String password = split[1];
            //步骤④通过输出流向客户端发送响应信息
            os = socket.getOutputStream();
            pw = new PrintWriter(os);
            //模拟验证账号密码是否正确
            if ("admin".equals(name) && "123456".equals(password)) {
                pw.write("login success!");
            } else {
                pw.write("login failed!!!");
            }
            pw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //步骤⑤关闭相关资源
            try {
                if (pw != null)
                    pw.close();
                if (os != null)
                    os.close();
                if (br != null)
                    br.close();
                if (isr != null)
                    isr.close();
                if (is != null)
                    is.close();
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
